package xxl.config.clock.rPic;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Objects;

/**
 * @Author: xixil
 * @Date: 2020/3/20
 */
public class GetPic {

    public static void getHtml() {

        HttpResponse httpResponse =
                HttpUtil.createPost("http://yunjie.f06.87yun.club/st/")
                        .form("qqlx", "r")
                        .execute();


        String dom = httpResponse.body();

        int clazz = dom.indexOf("img1");

        int start =
                dom.indexOf("i.pixiv", clazz);
        int end =
                dom.indexOf("\"", start);

        String urlStr = "https://" + dom.substring(start, end);

        System.out.print(urlStr);

        try {
            saveFile(urlStr);
        } catch (Exception e) {
            System.out.printf("--------------------ERROR");

        }


    }

    public static void saveFile(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        URLConnection con = url.openConnection();

        con.setRequestProperty("User-agent", "	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");

        InputStream is = con.getInputStream();

        int name =
                urlStr.lastIndexOf("/");

        String fileName =
                urlStr.substring(name);

//        String fileName = RandomUtil.randomNumbers(10) + ".png";
//        String fileName = urlStr.replace("/","");
//        String fileName = urlStr;

        String mkdir = "C:\\Users\\65782\\Desktop\\test\\";

        File mkdirFile = new File(mkdir);

        boolean isExit =
                Arrays.stream(Objects.requireNonNull(mkdirFile.listFiles())).anyMatch(item -> item.getName().equals(fileName));
        if (isExit) {
            return;
        }

        String filePath = mkdir + fileName;

        OutputStream outputStream = new FileOutputStream(filePath);

        IoUtil.copy(is, outputStream);

        outputStream.close();

        is.close();

        System.out.println("------------------SUCCESS");
    }

    public static void main(String[] args) {
        while (true) {
            GetPic.getHtml();
        }
    }
}
